package skyinline.EX01.SungJuk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLRecoverableException;
import java.util.Scanner;

public class EX01_SungJukDAO implements EX01_ISungJukDAO {

	private String DRV = "oracle.jdbc.driver.OracleDriver";
	private String URL = "jdbc:oracle:thin:skyinline/123456@112.216.253.125:1521:xe";
	private String insertSQL = " insert into EX01_SungJuk values ( student_no.nextval, ?, ?, ?, ?, ?, ?, ?) ";
	Scanner sc = new Scanner(System.in);
	
	@Override
	public boolean insertSungJuk(EX01_SungJukVO ev) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		boolean result = false;
		
		while ( true ) {
			System.out.print("저장하시겠습니까? [ 01 ] YES     [ 02 ] NO      :      ");
			switch ( sc.next()) {
			case "01" : case "1" :
				try {
						conn = this.openDatabase();
						pstmt = conn.prepareStatement( insertSQL );
							pstmt.setString(1, ev.getStudent_Name());
							pstmt.setInt(2, ev.getStudent_Kor());
							pstmt.setInt(3, ev.getStudent_Eng());
							pstmt.setInt(4, ev.getStudent_Mat());
							pstmt.setInt(5, ev.getStudent_Tot());
							pstmt.setFloat(6, ev.getStudent_Avg());
							pstmt.setString(7, ev.getStudent_Grd());
						pstmt.executeUpdate();
						result = true;
					} catch ( SQLRecoverableException se ) {
						System.err.println("데이터베이스 연결에 실패했습니다. 네트워크를 확인하세요.");
						System.exit ( 0 );
					} catch ( Exception ex ) {
						ex.printStackTrace();
					} finally {
						this.closeDatabase( conn, pstmt, null );
					}
					return result;
			case "02" : case "2" :
				while ( true ) {
					System.out.print("성적을 추가로 등록하시겠습니까? [ 01 ] YES     [ 02 ] NO     :     ");
					switch ( sc.next() ) {
					case "01 " : case "1" :
						new EX01_SungJukService().createSungJuk();
					case "02" : case "2" :
						System.err.println("시스템을 종료합니다.");
						System.exit( 0 );
					default :
						System.err.println("잘못 선택하셨습니다. 다시 입력하세요.");
					}
				}
			default : 
				System.err.println("잘못 선택하셨습니다. 다시 입력하세요.");
			}
		}
	}
		private Connection openDatabase() {
			try {
				Class.forName( DRV );
				return DriverManager.getConnection( URL );
			} catch ( Exception e ) {
				e.printStackTrace();
			}
			return null;
		}
		
		private void closeDatabase(Connection c, PreparedStatement p, ResultSet r) {
			if ( r != null ) try { r.close(); r = null; } catch ( Exception e ) {}
			if ( p != null ) try { p.close(); p = null; } catch ( Exception e ) {}
			if ( c != null ) try { c.close(); c = null; } catch ( Exception e ) {}
		}

	}
